﻿/*
 * 由SharpDevelop创建。
 * 用户： Administrator
 * 日期: 2024/12/1
 * 时间: 16:52
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Net;
using System.Text;
using LitJson;

using System.IO;
using System.Reflection; 


namespace weather
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
			
			InitializeComponent();
			
			string inipath=Directory.GetCurrentDirectory()+"\\setting.ini"; 
			int x=int.Parse(iniHelper.Read("Weather","left",inipath));
			int y=int.Parse(iniHelper.Read("Weather","top",inipath));
			this.Location=new Point(x,y);
			 
			int w=int.Parse(iniHelper.Read("Weather","width",inipath));
			int h=int.Parse(iniHelper.Read("Weather","height",inipath));
			this.Size=new Size(w,h);
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			string weather="";
			string weaimg="";
			string tem="";
			string humidity="";
			
			
			string type=iniHelper.Read("Weather","type",inipath);
			switch (type) {
				case "1":
				string cityid=iniHelper.Read("Weather","cityid",inipath);
				string appid=iniHelper.Read("Weather","appid",inipath);
				string appsecret=iniHelper.Read("Weather","appsecret",inipath);
	             if (appid=="") {
	             	MessageBox.Show("请到setting.ini设置appid");
	             	this.Close();
				} 
	    
				string info=GetWebClient("https://v0.yiketianqi.com/api?unescape=1&version=v91&appid="+appid+"&appsecret="+appsecret+"&ext=&cityid=CN"+cityid);
				JsonData json=JsonMapper.ToObject(info);  //https://blog.csdn.net/DoyoFish/article/details/81976181
				JsonData data=json["data"];
				weather=data[0]["wea"].ToString();
				weaimg=data[0]["wea_img"].ToString();
				tem=data[0]["tem"].ToString()+"°C";
				humidity=data[0]["humidity"].ToString();
				pictureBox1.Image=Image.FromFile(Directory.GetCurrentDirectory()+"\\weaimg\\"+weaimg+".png");
				break;
				
				case "2":
				string cityid2=iniHelper.Read("weather","cityid",inipath);
				string json2=
					GetWebClient("http://t.weather.itboy.net/api/weather/city/"+cityid2);
				JsonData txt=JsonMapper.ToObject(json2);
				tem=txt["data"]["wendu"].ToString()+"°C";
				humidity=txt["data"]["shidu"].ToString();
				weather=txt["data"]["forecast"][0]["type"].ToString();
				label1.Text=weather+" "+tem;
				pictureBox1.Image=Image.FromFile(Directory.GetCurrentDirectory()+"\\res\\"+weather+".ico");
				break;
				
				case "3":
				string cityid3=iniHelper.Read("weather","cityid",inipath);
				string tm=DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
			//	string url="http://d1.weather.com.cn/dingzhi/101131001.html?_="+tm; //简单天气信息
			//	string url2="http://toy1.weather.com.cn/search?cityname=%E4%BC%8A%E5%AE%81"; //查看城市对应id
				string url3="http://d1.weather.com.cn/sk_2d/"+cityid3+".html?_="+tm; //详细天气信息
				 
				string json3=httpGet(url3,"d1.weather.com.cn").Replace("var dataSK=","");
				JsonData txt2=JsonMapper.ToObject(json3);
				tem=txt2["temp"].ToString()+"°C";
				humidity=txt2["sd"].ToString();
				weather=txt2["weather"].ToString();
				weaimg=txt2["weathercode"].ToString();
				label1.Text=weather+" "+tem;
				pictureBox1.Image=Image.FromFile(Directory.GetCurrentDirectory()+"\\res\\weather_icons_blue\\"+weaimg+".ico");
				break;
			}
			//
		}
		
		private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            //默认命名空间+文件夹名+.[注意]
            string resourceName = "weather." + new AssemblyName(args.Name).Name + ".dll";

            // LogHelper.Debug("在加载资源：" + resourceName);
            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
            {
                if (stream != null)
                {
                    byte[] assemblyData = new byte[stream.Length];
                    stream.Read(assemblyData, 0, assemblyData.Length);
                    return Assembly.Load(assemblyData);
                }

                return null;
            }
        }
		void Timer1Tick(object sender, EventArgs e)
		{
			string inipath=Directory.GetCurrentDirectory()+"\\setting.ini"; 
			string color=iniHelper.Read("Topbar","backcolor",inipath);
			this.BackColor =ColorTranslator.FromHtml(color); 
		}
		
		private string GetWebClient(string url)
		{
        	ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
		    
		    string strHTML = "";
		    WebClient myWebClient = new WebClient();
		    Stream myStream = myWebClient.OpenRead(url);
		    StreamReader sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("utf-8"));
		    strHTML = sr.ReadToEnd();
		    myStream.Close();
		    return strHTML;
		}
        public static string httpGet(string Url,string host)
        {
            string retString = string.Empty;
            //System.GC.Collect();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Proxy = null;
            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "text/html";
            request.Host=host;
            request.Referer="http://www.weather.com.cn/";
            request.AutomaticDecompression = DecompressionMethods.GZip;
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }catch(Exception ex){
                //抛出异常返回具体错误消息
                retString = ex.Message;
            }
            return retString;
        } 
	}
}
